//package net.tinyos.tools;

import java.io.*;
import net.tinyos.message.*;
import net.tinyos.packet.*;
import net.tinyos.util.*;
import net.tinyos.tools.PrintfMsg;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TimePrintfClient implements MessageListener {

  private MoteIF moteIF;
  
  public TimePrintfClient(MoteIF moteIF) {
    this.moteIF = moteIF;
    this.moteIF.registerListener(new PrintfMsg(), this);
  }

  public void messageReceived(int to, Message message) {
    PrintfMsg msg = (PrintfMsg)message;
    
    SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSS");
    String ts = dateFormat.format(new Date());
    System.out.print(ts+": ");

    for(int i=0; i<PrintfMsg.totalSize_buffer(); i++) {
      char nextChar = (char)(msg.getElement_buffer(i));
      if(nextChar != 0)
        System.out.print(nextChar);
    }
  }
  
  private static void usage() {
    System.err.println("usage: PrintfClient [-comm <source>]");
  }
  
  public static void main(String[] args) throws Exception {
    String source = null;
    if (args.length == 2) {
      if (!args[0].equals("-comm")) {
	       usage();
	       System.exit(1);
      }
      source = args[1];
    }
    
    PhoenixSource phoenix;
    if (source == null) {
      phoenix = BuildSource.makePhoenix(PrintStreamMessenger.err);
    }
    else {
      phoenix = BuildSource.makePhoenix(source, PrintStreamMessenger.err);
    }
    
    System.out.print(phoenix);
    MoteIF mif = new MoteIF(phoenix);
    TimePrintfClient client = new TimePrintfClient(mif);
  }
}
